package com.hwpt.chesedemo.presentation.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.hwpt.chesedemo.presentation.theme.strings
import com.hwpt.chesedemo.presentation.viewmodel.HomeViewModel
import com.hwpt.chesedemo.presentation.viewmodel.MenuItem

@Composable
fun HomeScreen(
    navController: NavController,
) {
    val strings = strings()
    val configuration = LocalConfiguration.current
    val screenWidth = configuration.screenWidthDp.dp
    val screenHeight = configuration.screenHeightDp.dp

    val viewModel = androidx.lifecycle.viewmodel.compose.viewModel<HomeViewModel>()
    val layoutParams = viewModel.getLayoutParameters(screenWidth)

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                brush = Brush.verticalGradient(
                    colors = listOf(Color(0xFF6A11CB), Color(0xFF2575FC))
                )
            )
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = layoutParams.horizontalPadding, vertical = layoutParams.verticalPadding),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.SpaceBetween
        ) {
            // 顶部标题区域
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    text = strings.appTitle,
                    fontSize = layoutParams.titleFontSize,
                    fontWeight = FontWeight.Bold,
                    color = Color.White,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.padding(bottom = 8.dp)
                )

                Text(
                    text = strings.appSubtitle,
                    fontSize = layoutParams.subtitleFontSize,
                    color = Color.White.copy(alpha = 0.9f),
                    textAlign = TextAlign.Center,
                    modifier = Modifier.padding(bottom = 16.dp)
                )
            }

            // 菜单卡片区域 - 使用固定高度
            AdaptiveMenuGrid(
                navController = navController,
                screenWidth = screenWidth,
                screenHeight = screenHeight,
                viewModel = viewModel,
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f, fill = true) // 使用权重确保不超出屏幕
            )
        }
    }
}

@Composable
private fun AdaptiveMenuGrid(
    navController: NavController,
    screenWidth: Dp,
    screenHeight: Dp,
    viewModel: HomeViewModel,
    modifier: Modifier = Modifier
) {
    val menuItems = viewModel.getMenuItems()
    val columns = viewModel.getGridColumns(screenWidth)

    // 计算可用高度，确保5个选项能在一屏内显示
    val availableHeight = screenHeight * 0.6f // 留出空间给标题和其他元素

    if (columns == 1) {
        // 单列布局
        Column(
            modifier = modifier,
            verticalArrangement = Arrangement.spacedBy(12.dp) // 减少间距
        ) {
            menuItems.forEach { menuItem ->
                MenuCard(
                    menuItem = menuItem,
                    navController = navController,
                    modifier = Modifier.fillMaxWidth(),
                    isSingleColumn = true,
                    viewModel = viewModel,
                    screenWidth = screenWidth,
                    screenHeight = availableHeight,
                    itemCount = menuItems.size
                )
            }
        }
    } else {
        // 网格布局
        LazyVerticalGrid(
            columns = GridCells.Fixed(columns),
            modifier = modifier,
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
            userScrollEnabled = false // 禁用滚动，确保在一屏内
        ) {
            items(menuItems) { menuItem ->
                MenuCard(
                    menuItem = menuItem,
                    navController = navController,
                    modifier = Modifier.fillMaxWidth(),
                    isSingleColumn = false,
                    viewModel = viewModel,
                    screenWidth = screenWidth,
                    screenHeight = availableHeight,
                    itemCount = menuItems.size
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun MenuCard(
    menuItem: MenuItem,
    navController: NavController,
    modifier: Modifier = Modifier,
    isSingleColumn: Boolean = false,
    viewModel: HomeViewModel,
    screenWidth: Dp,
    screenHeight: Dp,
    itemCount: Int
) {
    // 动态计算卡片高度，确保5个选项能在一屏内显示
    val cardHeight = if (isSingleColumn) {
        // 单列：每个卡片高度为可用高度的1/5
        (screenHeight / itemCount) - 12.dp // 减去间距
    } else {
        val columns = viewModel.getGridColumns(screenWidth)
        // 网格布局：计算行数和每行高度
        val rows = (itemCount + columns - 1) / columns // 向上取整
        (screenHeight / rows) - 12.dp // 减去间距
    }

    val cardPadding = 16.dp
    val iconFontSize = viewModel.getIconFontSize(screenWidth, isSingleColumn)
    val titleFontSize = viewModel.getTitleFontSize(screenWidth, isSingleColumn)
    val descriptionFontSize = viewModel.getDescriptionFontSize(screenWidth, isSingleColumn)

    Card(
        onClick = {
            navController.navigate(menuItem.route)
        },
        modifier = modifier
            .height(cardHeight.coerceAtLeast(80.dp)), // 最小高度保证可点击
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.15f)
        ),
        shape = RoundedCornerShape(16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        if (isSingleColumn) {
            Row(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Start
            ) {
                Text(
                    text = menuItem.icon,
                    fontSize = iconFontSize,
                    color = Color.White,
                    modifier = Modifier.padding(end = 16.dp)
                )

                Column(
                    modifier = Modifier.weight(1f)
                ) {
                    Text(
                        text = menuItem.title,
                        fontSize = titleFontSize,
                        fontWeight = FontWeight.Bold,
                        color = Color.White,
                        modifier = Modifier.padding(bottom = 4.dp)
                    )

                    Text(
                        text = menuItem.description,
                        fontSize = descriptionFontSize,
                        color = Color.White.copy(alpha = 0.9f),
                        textAlign = TextAlign.Start,
                        maxLines = 2 // 限制描述行数
                    )
                }
            }
        } else {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(cardPadding),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center // 垂直居中
            ) {
                Text(
                    text = menuItem.icon,
                    fontSize = iconFontSize,
                    color = Color.White,
                    modifier = Modifier.padding(bottom = 8.dp)
                )

                Text(
                    text = menuItem.title,
                    fontSize = titleFontSize,
                    fontWeight = FontWeight.Bold,
                    color = Color.White,
                    modifier = Modifier.padding(bottom = 4.dp),
                    textAlign = TextAlign.Center
                )

                Text(
                    text = menuItem.description,
                    fontSize = descriptionFontSize,
                    color = Color.White.copy(alpha = 0.9f),
                    textAlign = TextAlign.Center,
                    maxLines = 2, // 限制描述行数
                    lineHeight = descriptionFontSize * 1.2f
                )
            }
        }
    }
}